<template>
  <div id="Params">
     <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>商品管理</el-breadcrumb-item>
  <el-breadcrumb-item>分类参数</el-breadcrumb-item>
</el-breadcrumb>
<!-- 卡片视图card -->
<el-card class="box-card">
  <!-- 提示信息 -->
    <el-alert
    title="注意：只允许为第三级分类设置相关参数"
    type="warning"
    show-icon>
  </el-alert>
<!-- 选择商品分类 -->
<el-form style="margin-top:12px">
<el-form-item label="选择商品分类：">
    <el-cascader
    change-on-select
    clearable
    v-model="selectKeys"
    expand-trigger="hover"
    :options="allCateList"
    :props="expandTrigger"
    @change="handleChange"></el-cascader>
    </el-form-item>
  </el-form>
  <!-- Tab页 -->
  <el-tabs v-model="activeName" @tab-click="handleClick">
      <!-- 动态 -->
    <el-tab-pane label="动态参数" name="many">
      <el-button type="primary" :disabled='isBtnShow' @click="insertParams">添加参数</el-button>
      <!-- 动态表格区 -->
  <el-table
  style="margin-top:15px"
    border
    :data="manyTableList">
     <el-table-column
     type="expand"
      >
      <template slot-scope="scope">
    <div class="develop">
  		<div class="Tag"> 
        <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index,scope.row)">{{item}}</el-tag>
      <el-input
  class="input-new-tag"
  v-if="scope.row.inputVisible"
  v-model="scope.row.inputValue"
  ref="saveTagInput"
  size="small"
  @keyup.enter.native="handleInputConfirm(scope.row)"
  @blur="handleInputConfirm(scope.row)"
>
</el-input>
<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
      </div>
      </div>
  		</template>
    </el-table-column>
    <el-table-column
      type="index"
      label="#"
      >
    </el-table-column>
   <el-table-column
      property="attr_name"
      label="参数名称"
      >
    </el-table-column>
    <el-table-column label="操作">
  		<template slot-scope="scope">
  			<el-button type="primary" icon="el-icon-edit" size="mini" @click="editParams(scope.row.attr_id)">编辑</el-button>
  			<el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
  		</template>
    </el-table-column>
  </el-table>
    </el-tab-pane>
    <!-- 静态 -->
    <el-tab-pane label="静态属性" name="only">
      <el-button type="primary" :disabled='isBtnShow' @click="insertParams">添加属性</el-button>
       <!-- 静态表格区 -->
  <el-table
  style="margin-top:15px"
    border
    :data="onlyTableList">
      <el-table-column
     type="expand"
      >
      <template slot-scope="scope">
         <div class="develop">
  		<div class="Tag"> <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index,scope.row)">{{item}}</el-tag>
      <el-input
  class="input-new-tag"
  v-if="scope.row.inputVisible"
  v-model="scope.row.inputValue"
  ref="saveTagInput"
  size="small"
  @keyup.enter.native="handleInputConfirm(scope.row)"
  @blur="handleInputConfirm(scope.row)"
>
</el-input>
<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
      </div>
       </div>
  		</template>
    </el-table-column>
    <el-table-column
      type="index"
      label="#"
      >
    </el-table-column>
   <el-table-column
      property="attr_name"
      label="属性名称"
      >
    </el-table-column>
    <el-table-column label="操作">
  		<template slot-scope="scope">
  			<el-button type="primary" icon="el-icon-edit" size="mini" @click="editParams(scope.row.attr_id)">编辑</el-button>
  			<el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
  		</template>
    </el-table-column>
  </el-table>
    </el-tab-pane>
  </el-tabs>
   <!-- 弹出对话框  两个用一个封装-->
<el-dialog v-model="manyTableList" :title="titleDialog" :visible.sync="dialogParams" @close='addCateDialog'>
  <el-form :model="addForm"  :rules="rules" ref="ruleForm" label-width="100px">
    <el-form-item :label="labelDialog" prop="attr_name">
      <el-input v-model="addForm.attr_name" style="width:36%"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="offForm">取 消</el-button>
    <el-button type="primary" @click="sureForm">确 定</el-button>
  </div>
</el-dialog>
 <!-- 修改弹窗对话框  两个用一个封装-->
<el-dialog v-model="manyTableList" :title="editTitleDialog" :visible.sync="editDialog" @close='editCateDialog'>
  <el-form :model="editForm"  :rules="rules" ref="editRuleForm" label-width="100px">
    <el-form-item :label="labelDialog" prop="attr_name">
      <el-input v-model="editForm.attr_name" style="width:36%"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="editOffForm">取 消</el-button>
    <el-button type="primary" @click="editSureForm">确 定</el-button>
  </div>
</el-dialog>

</el-card>
  </div>
</template>

<script>
export default {
  data(){
    return{
      allCateList:[],
      expandTrigger:{
        value:'cat_id',
        label:'cat_name',
        children:'children'
        },
        selectKeys:[],
        //被激活的页签 many和only是接口参数字段
        activeName: 'many',
        //动态属性表格列表数据
        manyTableList:[],
         //静态属性表格列表数据
        onlyTableList:[],
        dialogParams:false,
         rules:{
          attr_name:[
            { required: true, message: '请输入参数名称', trigger: 'blur' },
            { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
          ],
        },
        addForm:{},
        editForm:{},
        editDialog:false,
       
    }
  },
  created(){
    this.getAllCate()
  },
  methods:{
    // 获取分类数据列表
    async getAllCate(){
      const {data:res}=await this.$http.get('categories')
      if(res.meta.status!==200){
        return this.$message.error('获取分类数据失败')
      }
      this.allCateList=res.data
    },
    //选择框会触发这个函数
    async handleChange(){
     
      this.getParamsData()
    },
    async handleClick(tab, event) {
      console.log(tab, event);
       this.getParamsData()
    },
    //获取参数的列表数据
    async getParamsData(){
      console.log(this.selectKeys);
      // 判断选择框只能选择第三级别
      if(this.selectKeys.length!==3){
        this.selectKeys=[]
         //判断如果选择框中选择的不是3级  就隐藏表格数据为空
         this.manyTableList=[]
         this.onlyTableList=[]
        return
      }
      //根据所选分类的id获取对应的参数
      const {data:res}=await this.$http(`categories/${this.cateId}/attributes`,{params:{sel:this.activeName}})


      if(res.meta.status!==200){
        return this.$message.error('获取参数列表失败')
      }

      //展开行  返回的数据把字符串转为数组
      res.data.forEach(item=>{
        item.attr_vals=item.attr_vals?
        item.attr_vals.split(' '):[]
        //控制文本框的显示和隐藏
        item.inputVisible=false
        //文本框中输入的值
        item.inputValue=''
      })

      if(this.activeName === 'many'){
        this.manyTableList=res.data
      }else{
        this.onlyTableList=res.data
      }
    },
    insertParams(){
      this.dialogParams=true
    },
    addCateDialog(){
      this.$refs.ruleForm.resetFields()
    },
    editCateDialog(){
       this.$refs.editRuleForm.resetFields()
    },
    offForm(){
      this.dialogParams=false
    },
    sureForm(){
      this.dialogParams=false
      this.$refs.ruleForm.validate(async valid=>{
        if(!valid) return
        const {data:res}=await this.$http.post(`categories/${this.cateId}/attributes`,{attr_name:this.addForm.attr_name,attr_sel:this.activeName})
        if(res.meta.status!==201){
          return this.$message.error('添加参数失败')
        }
        this.$message.success('添加参数成功')
        this.getParamsData()
      })
    },
    async editParams(id){
      this.editDialog=true
      const {data:res}=await this.$http.get(`categories/${this.cateId}/attributes/${id}`,{params:{attr_sel:this.activeName}})
      if(res.meta.status!==200){
          return this.$message.error('查询失败')
        }
        this.$message.success('查询成功')
        this.editForm=res.data
        this.getParamsData()
    },
    removeParams(id){
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
      }).then(async () => {
      const { data:res }=await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if(res.meta.status === 200){
      this.$message({
        type: 'success',
        message: '删除成功!'
      });
      this.getParamsData()
      }
      
    }).catch(() => {
      this.$message({
        type: 'info',
        message: '已取消删除'
      });          
    });
    },
    editOffForm(){
      this.editDialog=false
    },
    editSureForm(){
       this.$refs.editRuleForm.validate(async valid=>{
         if(!valid) return
         const {data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,{attr_name:this.editForm.attr_name,attr_sel:this.activeName})
          if(res.meta.status!==200){
          return this.$message.error('修改失败')
        }
        this.$message.success('修改成功')
        this.editForm=res.data
        this.getParamsData()
        this.editDialog=false
       })
    },
    async handleInputConfirm(row){
      //判断tag里面输入的合不合法
      if(row.inputValue.trim().length ===0){
        row.inputVisible=''
        row.inputVisible=false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue='',
      row.inputVisible=false
      //添加Tag接口
      // const {data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{attr_name:row.attr_name,attr_sel:row.attr_sel,attr_vals:row.attr_vals.join(' ')})
      //  if(res.meta.status!==200){
      //     return this.$message.error('添加失败')
      //   }
      //   this.$message.success('添加成功')
      this.saveAttrVals(row)
    },
    //添加Tag接口拿出来单独声明
    async saveAttrVals(row){
      const {data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{attr_name:row.attr_name,attr_sel:row.attr_sel,attr_vals:row.attr_vals.join(' ')})
       if(res.meta.status!==200){
          return this.$message.error('修改参数项失败')
        }
        this.$message.success('修改参数项成功')
    },
    showInput(row){
      row.inputVisible=true
      //让文本框自动获得焦点
      this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //移除Tag
    handleClose(index,row){
      row.attr_vals.splice(index,1)
      this.saveAttrVals(row)
    }
  },
  computed:{
    isBtnShow(){
      if(this.selectKeys.length!==3){
        return true
      }
      return false
    },
    cateId(){
      if(this.selectKeys.length === 3){
        return this.selectKeys[2]
      }
      return null
    },
    titleDialog(){
      if(this.activeName === 'many'){
        return '添加动态参数'
      }
      return '添加静态属性'
    },
    editTitleDialog(){
      if(this.activeName === 'many'){
        return '修改动态参数'
      }
      return '修改静态属性'
    },
    labelDialog(){
      if(this.activeName === 'many'){
        return '动态参数：'
      }
      return '静态属性：'
    }
  }
}
</script>

<style lang="less" scoped>
#Params{
  .box-card{
    margin: 20px 0;
    .develop{
       display: flex;
        justify-content: center;
        align-items: center;
       padding: 20px 0;
      .Tag{
        display: flex;
       flex-wrap: wrap;
       justify-content: flex-start;
        width: 1000px;
      
        .el-tag{
          margin: 6px;
         
        }
        .input-new-tag{
          width: 120px;
            margin: 6px;
        }
      }
    }
  }
}
</style>